﻿using Common;
using gregn6Lib;
using NursingFormSystem.Common;
using NursingFormSystem.Model;
using SQLDLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NursingFormSystem.RiskAssessment
{
    public partial class RiskPrint : Form
    {
        #region 变量声明
        private GridppReport Report = new GridppReport();
        NurFormsService.NursingForm formService = new NurFormsService.NursingForm();
        PatientInfo PatientInfo;
        DateTime Start;
        DateTime End;
        Tb_User LoginUser;
        ElectronicSignature es;
        #endregion
        #region 构造函数
        public RiskPrint(Tb_User loginUser, PatientInfo patientInfo,DateTime StartDate, DateTime EndDate)
        {
            InitializeComponent();
            PatientInfo = patientInfo;
            LoginUser = loginUser;
            es = new ElectronicSignature(this.LoginUser);
            Start = StartDate;
            End = EndDate;
            //载入报表模板数据
            Report.LoadFromFile(System.Windows.Forms.Application.StartupPath + @"\GRFModel\Ydhl_GRF\住院病人压疮风险评估护理单.grf");
            //设置与数据源的连接串，因为在设计时指定的数据库路径是绝对路径。
            Report.ConnectionString = Utility.GetDatabaseConnectionString();
            //连接报表取数事件
            Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
            //设定查询显示器关联的报表
            axGRPrintViewer1.Report = Report;
        }
        #endregion

        #region 连接报表取数事件
        private void ReportFetchRecord()
        {
            var ret = formService.GetNursingFormRecordByDate(this.PatientInfo.PATIENT_ID,PatientInfo.VISIT_ID, (int)FormType.RiskSore, Start, End);
            DataTable dt = new DataTable();
            if (ret.Code == 1)
            {
                CreateDataTableHead(dt);
                //时间降序
                List<NursingFormRecord> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<NursingFormRecord>>(ret.D);
                list = list.OrderByDescending(p => p.AssessmentDate).ToList();
                //取最新的 而且 预后 患者签字 与患者关系 皮肤情况四项 有一项非空的
                RiskSore new_ps = XmlUtil.XMLToObject<RiskSore>(list[0].NursingFormData, Encoding.UTF8);
                //取四项有一项非空的 取到非空的马上停止
                foreach (var item in list)
                {
                    NursingFormRecord rd = item;
                    RiskSore ps = XmlUtil.XMLToObject<RiskSore>(rd.NursingFormData, Encoding.UTF8);
                    new_ps = ps;
                    if (!string.IsNullOrEmpty(new_ps.YuHou) && new_ps.YuHou.IndexOf("1") >= 0) break;
                    if (!string.IsNullOrEmpty(new_ps.HuanZheQianZi)) break;
                    if (!string.IsNullOrEmpty(new_ps.YuHuanZheGuanXi)) break;
                    if (!string.IsNullOrEmpty(new_ps.HuanZhePiFuQingGuang)) break;
                }

                for (int i = 0; i < list.Count; i++)
                {
                    NursingFormRecord rd = list[i];
                    RiskSore ps = XmlUtil.XMLToObject<RiskSore>(rd.NursingFormData, Encoding.UTF8);
                    string image1 = "";
                    string HS = ps.HuShiQianMing;
                    if (!string.IsNullOrEmpty(HS))
                    {
                        image1 = es.GetElectricSignBase64(rd.AreaId, ps.HuShiQianMing);
                    }
                    string image2 = "";
                    string HSZ = ps.HuShiZhangQianMing;
                    if (!string.IsNullOrEmpty(HSZ))
                    {
                        image2 = es.GetElectricSignBase64(rd.AreaId, ps.HuShiZhangQianMing);
                    }

                    dt.Rows.Add(
                        rd.PatientId,
                        rd.PatientName,
                        rd.DepartmentName,
                        rd.BedNo,
                        PatientInfo.AGE,
                        Convert.ToDateTime(rd.AssessmentDate),
                        ps.GanJue,
                        ps.ChaoShi,
                        ps.HuoDongLi,
                        ps.YiDongLi,
                        ps.MoChaLiHeJianQieLi,
                        ps.YingYang,
                        ps.ZongFen,
                        ps.TiWeiAnZhiYuBianHuan.Substring(0, 1) == "0" ? "" : "√",
                        ps.TiWeiAnZhiYuBianHuan.Substring(2, 1) == "0" ? "" : "√",
                        ps.TiWeiAnZhiYuBianHuan.Substring(4, 1) == "0" ? "" : "√",
                        ps.TiWeiAnZhiYuBianHuan.Substring(6, 1) == "0" ? "" : "√",
                        ps.TiWeiAnZhiYuBianHuan.Substring(8, 1) == "0" ? "" : "√",
                        ps.TiWeiAnZhiYuBianHuan.Substring(10, 1) == "0" ? "" : "√",
                        ps.JianYaYongJuYuShiYong.Substring(0, 1) == "0" ? "" : "√",
                        ps.JianYaYongJuYuShiYong.Substring(2, 1) == "0" ? "" : "√",
                        ps.JianYaYongJuYuShiYong.Substring(4, 1) == "0" ? "" : "√",
                        ps.JianYaYongJuYuShiYong.Substring(6, 1) == "0" ? "" : "√",
                        ps.PiFuHuLi.Substring(0, 1) == "0" ? "" : "√",
                        ps.PiFuHuLi.Substring(2, 1) == "0" ? "" : "√",
                        ps.PiFuHuLi.Substring(4, 1) == "0" ? "" : "√",
                        ps.PiFuHuLi.Substring(6, 1) == "0" ? "" : "√",
                        ps.PiFuHuLi.Substring(8, 1) == "0" ? "" : "√",
                        ps.PiFuHuLi.Substring(10, 1) == "0" ? "" : "√",
                        ps.YingYangZhiChi.Substring(0, 1) == "0" ? "" : "√",
                        ps.YingYangZhiChi.Substring(2, 1) == "0" ? "" : "√",
                        ps.YingYangZhiChi.Substring(4, 1) == "0" ? "" : "√",
                        ps.YingYangZhiChi.Substring(6, 1) == "0" ? "" : "√",
                        !Base.ESSwitch.Equals("on")? ps.HuShiQianMing:"",
                        !Base.ESSwitch.Equals("on")?ps.HuShiZhangQianMing:"",
                        //底部
                        new_ps.YuHou.Substring(0, 1),
                        new_ps.YuHou.Substring(2, 1),
                        new_ps.YuHou.Substring(4, 1),
                        new_ps.YuHou.Substring(6, 1),
                        new_ps.YuHou.Substring(8, 1),
                        new_ps.YuHou.Substring(10, 1),
                        new_ps.HuanZheQianZi,
                        new_ps.YuHuanZheGuanXi,
                        CutString(new_ps.HuanZhePiFuQingGuang, 300, "..."), //max 300字符
                        image1,
                        image2
                    );
                }
                //将 DataTable 的数据转储到 Grid++Report 的数据集中
                Utility.FillRecordToReport(Report, dt);
            }
            else if (ret.Code == 2)
            {
                CreateDataTableHead(dt);
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
                Utility.FillRecordToReport(Report, dt);
            }
            else if (ret.Code == 0)
            {
                MessageBox.Show(ret.M);
            }
        }

        /// <summary>
        /// 计算字符串的实际长度
        /// <param name="str">待计算的字符串</param>
        /// </summary>
        public static int StringLength(string str)
        {
            if (string.IsNullOrEmpty(str)) return 0;
            ASCIIEncoding ascEn = new ASCIIEncoding();
            Byte[] B = ascEn.GetBytes(str);
            int len = 0;
            for (int i = 0; i <= B.Length - 1; i++)
            {
                if (B[i] == 63)
                    len += 2;
                else
                    len++;
            }
            return len;
        }

        /// <summary>
        /// 按字符串实际长度截取定长字符串
        /// <param name="str">原字符串</param>
        /// <param name="len">要截取的长度(字节)</param>
        /// <param name="postfix">结尾符号</param>
        /// </summary>
        public static string CutString(string str, int len, string postfix)
        {
            if (string.IsNullOrEmpty(str)) return string.Empty;
            if (len == 0 || StringLength(str) < len) return str;
            ASCIIEncoding ascEn = new ASCIIEncoding();
            Byte[] B = ascEn.GetBytes(str);
            int i = 0, j = 0;
            for (i = 0; i <= B.Length - 1; i++)
            {
                if (B[i] == 63)
                    j += 2;
                else
                    j++;

                if (j >= len) break;
            }
            if (string.IsNullOrEmpty(postfix))
                return str.Substring(0, i + 1);
            else
                return str.Substring(0, i + 1) + postfix;
        }

        /// <summary>
        /// 加载列头
        /// </summary>
        /// <param name="dt"></param>
        private static void CreateDataTableHead(DataTable dt)
        {
            dt.Columns.Add("PatientId", typeof(string));
            dt.Columns.Add("PatientName", typeof(string));
            dt.Columns.Add("DepartmentName", typeof(string));//病区
            dt.Columns.Add("BedNo", typeof(string));
            dt.Columns.Add("Age", typeof(string));
            dt.Columns.Add("AssessmentDate", typeof(DateTime));//评估日期
            dt.Columns.Add("Feel", typeof(string));//感觉
            dt.Columns.Add("Damp", typeof(string));//潮湿
            dt.Columns.Add("Activity", typeof(string));//活动力
            dt.Columns.Add("Move", typeof(string));//移动力
            dt.Columns.Add("FrictionAndShear", typeof(string));//摩擦力和剪切力
            dt.Columns.Add("Nutrition", typeof(string));//营养
            dt.Columns.Add("TotalScore", typeof(string));//总分
            dt.Columns.Add("PosturalPlacement1", typeof(string));//体位安置与变换：定时变换体位
            dt.Columns.Add("PosturalPlacement2", typeof(string));//体位安置与变换：侧卧位尽量选择30°（特殊情况除外）
            dt.Columns.Add("PosturalPlacement3", typeof(string));//体位安置与变换：充分抬高足跟,可在小腿下垫一软枕
            dt.Columns.Add("PosturalPlacement4", typeof(string));//体位安置与变换：避免长时间抬高床头超30° （除非病情需要）
            dt.Columns.Add("PosturalPlacement5", typeof(string));//体位安置与变换：使用正确移动技巧移动移动患者
            dt.Columns.Add("PosturalPlacement6", typeof(string));//体位安置与变换：其他
            dt.Columns.Add("Decompression1", typeof(string));//减压用具与使用：使用气垫床
            dt.Columns.Add("Decompression2", typeof(string));//减压用具与使用：翻身枕丶靠枕丶水垫的使用
            dt.Columns.Add("Decompression3", typeof(string));//减压用具与使用：应用减压辅料（泡沫类或水胶体类）
            dt.Columns.Add("Decompression4", typeof(string));//减压用具与使用：其他
            dt.Columns.Add("SkinCare1", typeof(string));//皮肤护理：每天定时检查皮肤情况,特别是受压部位
            dt.Columns.Add("SkinCare2", typeof(string));//皮肤护理：加强基础护理,如床上擦浴丶更换衣物丶床单平整
            dt.Columns.Add("SkinCare3", typeof(string));//皮肤护理：保持皮肤清洁丶适度湿润
            dt.Columns.Add("SkinCare4", typeof(string));//皮肤护理：使用皮肤保护剂
            dt.Columns.Add("SkinCare5", typeof(string));//皮肤护理：大丶小便失禁者及时清洗或定时给予便器
            dt.Columns.Add("SkinCare6", typeof(string));//皮肤护理：其他
            dt.Columns.Add("NutritionSupport1", typeof(string));//营养支持：病情允许情况下高热量高蛋白饮食
            dt.Columns.Add("NutritionSupport2", typeof(string));//营养支持：口服丶鼻饲补充营养制剂
            dt.Columns.Add("NutritionSupport3", typeof(string));//营养支持：静脉高营养
            dt.Columns.Add("NutritionSupport4", typeof(string));//营养支持：适当补充硫酸锌等营养物质
            dt.Columns.Add("NurseSign", typeof(string));//护士签字
            dt.Columns.Add("NursingManageSign", typeof(string));//护士长签字
            dt.Columns.Add("Prognosis1", typeof(string));//预后：未发生
            dt.Columns.Add("Prognosis2", typeof(string));//预后：发生
            dt.Columns.Add("Prognosis3", typeof(string));//预后：愈合
            dt.Columns.Add("Prognosis4", typeof(string));//预后：好转
            dt.Columns.Add("Prognosis5", typeof(string));//预后：加重
            dt.Columns.Add("Prognosis6", typeof(string));//预后：无变化
            dt.Columns.Add("FamilySign", typeof(string));//患者/家属签字
            dt.Columns.Add("PatientRelation", typeof(string));//与患者关系
            dt.Columns.Add("SkinSituation", typeof(string));//患者皮肤情况
            dt.Columns.Add("ElectricSignBase641", typeof(string));
            dt.Columns.Add("ElectricSignBase642", typeof(string));

        }
        #endregion

        #region 窗体加载启动锐浪报表
        private void RiskPrint_Load(object sender, EventArgs e)
        {
            axGRPrintViewer1.Start();
        }
        #endregion
    }
}